package com.sky.wsp.office.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.sky.wsp.office.util.WpsUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.List;

/**
 * @author wangshaopeng@talkweb.com.cn
 * @desccription 在此输入描述
 * @date 2023/8/21
 */
@RestController
public class TestController {

    @GetMapping("/read")
    public String read(String path, ReadType type, Integer colNum, Integer dataColNum) {
//        path = "C:\\Users\\24044\\Desktop\\临时\\文件模板";
//        path = "C:\\Users\\24044\\Desktop\\临时\\文件模板\\表格模板";
        if (null == path) {
            return "path error!";
        }
        if (null == type) {
            return "type error!";
        }
        if (type != ReadType.head) {
            if (null == colNum) {
                return "colNum error!";
            }
            if (null == dataColNum) {
                return "dataColNum error!";
            }
        }
        File f = new File(path);
        readXlsx(f, type, colNum, dataColNum);

        return "OK";
    }

    private void readXlsx(File f, ReadType type, int colNum, int dataColNum) {
        if (f.isDirectory()) {
            String path = f.getAbsolutePath();
            String[] list = f.list();
            for (String xls : list) {
                if (xls.startsWith(".")) {
                    continue;
                }
                File c = new File(path + File.separator + xls);
                readXlsx(c, type, colNum, dataColNum);
            }
        } else {
            String name = f.getName();
            if (!name.endsWith(".xlsx")) {
                System.err.println("error file type: " + f.getPath());
            } else {
                switch (type) {
                    case head:
                        readXlsxHead(f);
                        break;
                    case data:
                        readXlsxData(f, colNum, dataColNum);
                        break;
                    case error:
                        readXlsxError(f, colNum, dataColNum);
                        break;
                    default:
                        System.err.println("error type: " + type);
                        break;
                }
            }
        }
    }

    private void readXlsxHead(File f) {
        ExcelReader reader = ExcelUtil.getReader(f, 0);
        try {
            List<String> sheetNames = reader.getSheetNames();
            String sheetName = sheetNames.get(0);
            System.out.print(f.getAbsolutePath());
            System.out.print("\t");
            System.out.print(sheetName);
            System.out.print("\t");
            List<List<Object>> read = reader.read(0, 1);
            if (!read.isEmpty()) {
                List<Object> cols = read.get(0);
                for (Object col : cols) {
                    System.out.print(col);
                    System.out.print("\t");
                }
            }
        } finally {
            if (null != reader) {
                reader.close();
            }
        }
        System.out.println();
    }

    private void readXlsxData(File f, int colNum, int dataColNum) {
        ExcelReader reader = ExcelUtil.getReader(f, 0);
        try {
            System.out.println(f.getName());
            List<List<Object>> read = reader.read();
            for (int i = 0; i < read.size(); i++) {
                if (i == 0) {
                    continue;
                }
                List<Object> cols = read.get(i);
                for (int i1 = 0; i1 < cols.size(); i1++) {
                    if (i1 < colNum) {
                        Object col = cols.get(i1);
                        if (i1 == (dataColNum - 1)) {
                            col = parseDate(col);
                        }
                        System.out.print(col);
                        System.out.print("\t");
                    }
                }
                System.out.println();
            }
        } finally {
            if (null != reader) {
                reader.close();
            }
        }
        System.out.println();
    }

    private void readXlsxError(File f, int colNum, int dataColNum) {
        ExcelReader reader = ExcelUtil.getReader(f, 0);
        try {
            System.out.println(f.getName());
            List<List<Object>> read = reader.read();
            for (int i = 0; i < read.size(); i++) {
                if (i == 0) {
                    continue;
                }
                List<Object> cols = read.get(i);
                if (!dataNotValid(cols, colNum, dataColNum)) {
                    // 数据正确则直接返回，不正确时才打印
                    continue;
                }
                for (int i1 = 0; i1 < cols.size(); i1++) {
                    if (i1 < colNum) {
                        Object col = cols.get(i1);
                        System.out.print(col);
                        System.out.print("\t");
                    }
                }
                System.out.println();
            }
        } finally {
            if (null != reader) {
                reader.close();
            }
        }
        System.out.println();
    }

    /**
     * 修正日期格式
     */
    private Object parseDate(Object col) {
        if (null == col) {
            return col;
        }
        String date = col.toString();
        if (date.endsWith("00:00:00")) {
            return date.split(" ")[0];
        }
        String[] parts;
        if (date.contains(".")) {
            parts = date.split("\\.");
        } else if (date.contains("/")) {
            parts = date.split("/");
        } else {
            parts = date.split("-");
        }
        if (parts.length == 1) {
            return parts[0] + "-01-01";
        }
        if (parts.length == 2) {
            String p2 = parts[1];
            if (p2.length() == 1) {
                p2 = "0" + p2;
            }
            return parts[0] + "-" + p2 + "-01";
        }
        String p1 = parts[0];
        String p2 = parts[1];
        String p3 = parts[2];
        if (p2.length() == 1) {
            p2 = "0" + p2;
        }
        if (p3.length() == 1) {
            p3 = "0" + p3;
        }
        return p1 + "-" + p2 + "-" + p3;
    }

    private boolean dataNotValid(List<Object> cols, int colNum, int dataColNum) {
        for (int i1 = 0; i1 < cols.size(); i1++) {
            if (i1 < colNum) {
                Object col = cols.get(i1);
                if (null == col) {
                    return true;
                }
                String v = col.toString();
                if (i1 == (dataColNum - 1)) {
                    return dateNotValid(v);
                } else if (v.contains("\n") || v.contains("?")) {
                    return true;
                }

            }
        }
        return false;
    }

    /**
     * 校验日期格式是否错误，错误返回true，正确返回false
     */
    private boolean dateNotValid(String date) {
        if (date.endsWith("00:00:00")) {
            return false;
        }
        String[] parts;
        if (date.contains(".")) {
            parts = date.split("\\.");
        } else if (date.contains("/")) {
            parts = date.split("/");
        } else {
            parts = date.split("-");
        }
        return parts.length != 3;
    }

    /**
     * 解析金山文档et类型文件
     *
     * @return
     */
    @GetMapping("parse-et")
    public String parseEt() {
        WpsUtil.createEt();
        WpsUtil.readEt();
        return "OK";
    }
}
